package bjx.com.kehu.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import bjx.com.kehu.R;
import bjx.com.kehu.contants.Constants;
import bjx.com.kehu.utils.DensityUtil;
import bjx.com.kehu.utils.GsonUtil;
import bjx.com.kehu.utils.MD5;
import bjx.com.kehu.utils.SPUtils;
import bjx.com.kehu.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Random;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jqc on 2017/10/21.
 */

public class RegisterActivity extends BaseActivity {

    ImageView mIVBack;
    TextView mTVTitle;
    EditText mETTel;
    EditText mETIdenCode;
    TextView mTVSendIdenCode;
    EditText mETUName;
    EditText mETPwd;
    EditText mETConfirmPwd;
    EditText mETZFB;
    CheckBox mCBLic;
    TextView mTVLic;
    TextView mTVReg;

    TimeCount time = new TimeCount(60000, 1000);
    PopupWindow pop; //商品属性窗口

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_reg);
        mIVBack = getViewById(R.id.back);
        mTVTitle = getViewById(R.id.title);
        mTVTitle.setText("注册");
        mETTel = getViewById(R.id.reg_et_tel);
        mETIdenCode = getViewById(R.id.reg_et_idencode);
        mTVSendIdenCode = getViewById(R.id.reg_tv_sendidencode);
        mETUName = getViewById(R.id.reg_et_uname);
        mETPwd = getViewById(R.id.reg_et_pwd);
        mETConfirmPwd = getViewById(R.id.reg_et_confirmpwd);
        mETZFB = getViewById(R.id.reg_et_zfb);
        mCBLic = getViewById(R.id.reg_cb_lic);
        mTVLic = getViewById(R.id.reg_tv_lic);
        mTVReg = getViewById(R.id.reg_tv_reg);
    }

    @Override
    protected void setListener() {
        mTVSendIdenCode.setOnClickListener(this);
        mIVBack.setOnClickListener(this);
        mTVLic.setOnClickListener(this);
        mTVReg.setOnClickListener(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.reg_tv_sendidencode:
                String tel2 = mETTel.getText().toString().trim();
                if(!Util.isMobileNO(tel2)) {
                    showToast("请填写正确手机号");
                    mETTel.requestFocus();
                    return;
                }

                String code = String.valueOf(new Random().nextInt(9000) + 1000);
                time.start();

                mEngine.sendIdenCode(code, tel2, MD5.getMessageDigest((tel2 + Constants.BASE_KEY + code).getBytes())).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String str = response.body().string();
                            JSONObject jo = new JSONObject(str);
                            int status = jo.getInt("status");
                            String msg = jo.getString("msg");
                            if (status == 200) {
                                showToast("验证码已发送");
                            } else if (status == 106) {
                                showToast("加盟商不存在");
                            } else if (status == 107) {
                                showToast("发送失败，请重新获取");
                            } else if (status == 100) {
                                showToast("获取失败");
                            } else {
                                showToast("获取异常");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                    }
                });


                break;
            case R.id.reg_tv_lic:
                startActivity(new Intent(mApp, WebViewActivity.class).putExtra("flag", 1)
                        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        .putExtra("url", Constants.LIC_URL)
                        .putExtra("title", "协议规则"));
                break;
            case R.id.reg_tv_reg:
                String tel = mETTel.getText().toString().trim();
                String uname = mETUName.getText().toString().trim();
                String pwd = mETPwd.getText().toString().trim();
                String confirmPwd = mETConfirmPwd.getText().toString().trim();
                String idenCode = mETIdenCode.getText().toString().trim();
                String key = MD5.getMessageDigest((tel + Constants.BASE_KEY + idenCode + pwd).getBytes());
                String alipay = mETZFB.getText().toString().trim();
                String deviceToken = String.valueOf(SPUtils.get(mApp, Constants.CHANNELID, "-1"));

                if (tel == null || tel.equals("")) {
                    showToast("手机号码不能为空");
                    mETTel.requestFocus();
                    return;
                }

                if(!Util.isMobileNO(tel)) {
                    showToast("手机号码格式不正确");
                    mETTel.requestFocus();
                    return;
                }
//
//                if (uname == null || uname.equals("")) {
//                    showToast("用户名不能为空");
//                    mETUName.requestFocus();
//                    return;
//                }

                if (pwd == null || pwd.equals("")) {
                    showToast("密码不能为空");
                    mETPwd.requestFocus();
                    return;
                }

                if (confirmPwd == null || confirmPwd.equals("") || !TextUtils.equals(pwd, confirmPwd)) {
                    showToast("两次密码不一致");
                    mETConfirmPwd.requestFocus();
                    return;
                }


                showNoticeDialog();
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTVSendIdenCode.setClickable(false);
            mTVSendIdenCode.setText(""+millisUntilFinished / 1000 +"s");
        }

        @Override
        public void onFinish() {
            mTVSendIdenCode.setText("重新获取");
            mTVSendIdenCode.setClickable(true);
        }
    }


    private  void register(){
//        if (!mCBLic.isChecked()) {
//            showToast("注册需要先同意“保驾行”相关协议。");
//            return;
//        }

        String tel = mETTel.getText().toString().trim();
        String uname = mETUName.getText().toString().trim();
        String pwd = mETPwd.getText().toString().trim();
        String confirmPwd = mETConfirmPwd.getText().toString().trim();
        String idenCode = mETIdenCode.getText().toString().trim();
        String key = MD5.getMessageDigest((tel + Constants.BASE_KEY + idenCode + pwd).getBytes());
        String alipay = mETZFB.getText().toString().trim();
        String deviceToken = String.valueOf(SPUtils.get(mApp, Constants.CHANNELID, "-1"));

        if (tel == null || tel.equals("")) {
            showToast("手机号码不能为空");
            mETTel.requestFocus();
            return;
        }

        if(!Util.isMobileNO(tel)) {
            showToast("手机号码格式不正确");
            mETTel.requestFocus();
            return;
        }
//
//                if (uname == null || uname.equals("")) {
//                    showToast("用户名不能为空");
//                    mETUName.requestFocus();
//                    return;
//                }

        if (pwd == null || pwd.equals("")) {
            showToast("密码不能为空");
            mETPwd.requestFocus();
            return;
        }

        if (confirmPwd == null || confirmPwd.equals("") || !TextUtils.equals(pwd, confirmPwd)) {
            showToast("两次密码不一致");
            mETConfirmPwd.requestFocus();
            return;
        }

        mEngine.register(tel, pwd, uname, idenCode, alipay, deviceToken, key).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");

                    if (status == 200) {
                        showToast("注册成功");
                        SPUtils.saveObject(mApp, "usermodel", GsonUtil.jsonToUserBean(jo.getString("result")));
                        finish();
                        if (LoginActivity.mInstants != null) {
                            LoginActivity.mInstants.finish();
                        }
                    } else if (status == 101) {
                        showToast("手机号与短信验证码不匹配");
                    } else if (status == 102) {
                        showToast("手机号已被注册");
                    } else if (status == 106) {
                        showToast("加盟商不存在");
                    } else if (status == 201) {
                        showToast("验证码已失效");
                    } else if (status == 202) {
                        showToast("验证码发送失败");
                    } else if (status == 203) {
                        showToast("验证码未发送");
                    } else if (status == 205) {
                        showToast("手机号已被注册");
                    } else if (status == 100) {
                        showToast("注册失败");
                    } else {
                        showToast("注册异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    /**
     * 显示软件更新对话框
     */
    public void showNoticeDialog() {

        setBackgroundAlpha((float) 0.7);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.dialog_agreement_tip, null);

        Double popHeight = DensityUtil.getScreenHeight(this) * 0.7;

        pop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
                popHeight.intValue());

        pop.update();
        pop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);  //设置弹出菜单可输入
        pop.setTouchable(true);       //设置popupwindow可点击
        pop.setOutsideTouchable(false);//设置popupwindow外部可点击

        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        pop.setFocusable(false);

        pop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        // 设置popWindow的显示和消失动画
        pop.setAnimationStyle(R.style.toastdig);

        // pop.setBackgroundDrawable(new BitmapDrawable());
        // 在底部显示
        pop.showAtLocation(view, Gravity.CENTER, 0, 0);

         TextView tv2 = (TextView) view.findViewById(R.id.cancel);
        TextView tv3 = (TextView) view.findViewById(R.id.ok);

 //
//        tv0.setText(R.string.soft_update_title);
//
//        tv2.setText(R.string.exit_account);
//
//        tv3.setText(R.string.soft_update_updatebtn);
        final WebView attr_descrip_tv = (WebView) view.findViewById(R.id.attr_descrip_tv);

         WebSettings settings = attr_descrip_tv.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptEnabled(true);//支持js
        //支持双击-前提是页面要支持才显示
//        webSettings.setUseWideViewPort(true);

        //支持缩放按钮-前提是页面要支持才显示
        settings.setBuiltInZoomControls(true);

        //设置客户端-不跳转到默认浏览器中
        attr_descrip_tv.setWebViewClient(new WebViewClient());

        attr_descrip_tv.loadUrl(Constants.LIC_URL);

        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBackgroundAlpha((float) 1.0);
                pop.dismiss();
            }
        });

        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBackgroundAlpha((float) 1.0);
                 register();
                pop.dismiss();

            }
        });
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

}
